package com.example.dianproject.controller;

import com.example.dianproject.entity.MeterReading;
import com.example.dianproject.service.MeterReadingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/meter-readings")
public class MeterReadingController {
    private static final Logger logger = LoggerFactory.getLogger(MeterReadingController.class);

    @Autowired
    private MeterReadingService meterReadingService;

    @PostMapping
    public ResponseEntity<MeterReading> create(@RequestBody MeterReading meterReading) {
        try {
            logger.info("Creating meter reading: {}", meterReading);
            if (meterReading.getMeterId() == null) {
                logger.error("Meter ID cannot be null");
                return ResponseEntity.badRequest().build();
            }
            if (meterReading.getPreviousReading() == null) {
                logger.error("Previous reading cannot be null");
                return ResponseEntity.badRequest().build();
            }
            if (meterReading.getCurrentReading() == null) {
                logger.error("Current reading cannot be null");
                return ResponseEntity.badRequest().build();
            }
            if (meterReading.getReadingDate() == null) {
                logger.error("Reading date cannot be null");
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(meterReadingService.save(meterReading));
        } catch (Exception e) {
            logger.error("Error creating meter reading: {}", meterReading, e);
            throw e;
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<MeterReading> findById(@PathVariable Long id) {
        try {
            logger.info("Finding meter reading by id: {}", id);
            MeterReading meterReading = meterReadingService.findById(id);
            return meterReading != null ? ResponseEntity.ok(meterReading) : ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("Error finding meter reading by id: {}", id, e);
            throw e;
        }
    }

    @GetMapping
    public ResponseEntity<List<MeterReading>> findAll() {
        try {
            List<MeterReading> readings = meterReadingService.findAll();
            logger.info("Found {} meter readings", readings.size());
            return ResponseEntity.ok(readings);
        } catch (Exception e) {
            logger.error("Error finding all meter readings", e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<MeterReading> update(@PathVariable Long id, @RequestBody MeterReading meterReading) {
        try {
            logger.info("Updating meter reading: {}", meterReading);
            if (!id.equals(meterReading.getReadingId())) {
                logger.error("ID mismatch: path ID = {}, body ID = {}", id, meterReading.getReadingId());
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(meterReadingService.save(meterReading));
        } catch (Exception e) {
            logger.error("Error updating meter reading: {}", meterReading, e);
            throw e;
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        try {
            logger.info("Deleting meter reading with id: {}", id);
            meterReadingService.deleteById(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("Error deleting meter reading with id: {}", id, e);
            throw e;
        }
    }

    @GetMapping("/meter/{meterId}")
    public ResponseEntity<List<MeterReading>> findByMeterId(@PathVariable Long meterId) {
        try {
            logger.info("Finding meter readings by meter id: {}", meterId);
            return ResponseEntity.ok(meterReadingService.findByMeterId(meterId));
        } catch (Exception e) {
            logger.error("Error finding meter readings by meter id: {}", meterId, e);
            throw e;
        }
    }

    @GetMapping("/date-range")
    public ResponseEntity<List<MeterReading>> findByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            logger.info("Finding meter readings between {} and {}", startDate, endDate);
            return ResponseEntity.ok(meterReadingService.findByDateRange(startDate, endDate));
        } catch (Exception e) {
            logger.error("Error finding meter readings by date range: {} to {}", startDate, endDate, e);
            throw e;
        }
    }

    @GetMapping("/meter/{meterId}/latest")
    public ResponseEntity<MeterReading> getLatestReading(@PathVariable Long meterId) {
        try {
            logger.info("Finding latest meter reading for meter: {}", meterId);
            MeterReading latestReading = meterReadingService.getLatestReading(meterId);
            return latestReading != null ? ResponseEntity.ok(latestReading) : ResponseEntity.notFound().build();
        } catch (Exception e) {
            logger.error("Error finding latest meter reading for meter: {}", meterId, e);
            throw e;
        }
    }

    @GetMapping("/count/pending")
    public ResponseEntity<Long> getPendingReadingsCount() {
        return ResponseEntity.ok(meterReadingService.getPendingReadingsCount());
    }

    @GetMapping("/count/monthly")
    public ResponseEntity<Long> getCurrentMonthReadingsCount() {
        return ResponseEntity.ok(meterReadingService.getCurrentMonthReadingsCount());
    }

    @GetMapping("/recent")
    public ResponseEntity<List<MeterReading>> getRecentReadings() {
        return ResponseEntity.ok(meterReadingService.getRecentReadings(5)); // 获取最近5条记录
    }
} 